package com.arena.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

public class Fetcher extends AsyncTask<String, String, String>{

	@Override
	protected String doInBackground(String... urls) {
		HttpClient httpclient = new DefaultHttpClient();		
		HttpGet httpget = new HttpGet(urls[0]);
		try {
		    HttpResponse response = httpclient.execute(httpget);
		    if(response != null) {
		        String line = "";
		        InputStream inputstream = response.getEntity().getContent();
		        line = convertStreamToString(inputstream);
		        Log.i("Question", line);
		        return line;
		    } else {		    	
		    	Log.e("Question", "Unable to complete your request");
		    }
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	/**
	 * Call this function after execute
	 */
	protected void onPostExecute(String result) {
    	Log.i("FeatchData", "onPostExecute:" + result);
    }
	
	/**
	 * Read data from input stream and return data
	 * @param is - input stream
	 * @return
	 */
	private String convertStreamToString(InputStream is) {
	    String line = "";
	    StringBuilder total = new StringBuilder();
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    try {
	        while ((line = rd.readLine()) != null) {
	            total.append(line);
	        }
	    } catch (Exception e) {
	    	Log.e("Question", e.getMessage());
	    }
	    return total.toString();
	}
}
